package com.msh.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msh.dao.VendingMachineDao;
import com.msh.dao.VmPolicyDao;
import com.msh.entity.NodeEntity;
import com.msh.entity.VendingMachineEntity;
import com.msh.entity.VmPolicyEntity;
import com.msh.service.NodeService;
import com.msh.service.VendingMachineService;
import com.msh.service.VmPolicyService;
import com.msh.viewmodel.Pager;
import com.msh.viewmodel.VendingMachineViewModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.LongFunction;
import java.util.stream.Collectors;

@Service
public class VmPolicyServiceImpl extends ServiceImpl<VmPolicyDao,VmPolicyEntity> implements VmPolicyService{

    @Autowired
    private VendingMachineDao vendingMachineDao;
    @Autowired
    private NodeService nodeService;

    @Override
    public Pager<VendingMachineViewModel> findVmListById(Long pageIndex, Long pageSize, Integer policyId) {
        Page<VmPolicyEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<VmPolicyEntity> qw = new LambdaQueryWrapper<>();
        if (policyId != null) {
            qw.eq(VmPolicyEntity::getPolicyId, policyId);
        }
        this.page(page, qw);
        Pager<VendingMachineViewModel> pager = new Pager<>();
        BeanUtils.copyProperties(page,pager);
        if (page.getSize() == 0) return pager;
        List<Long> vmIds = page.getRecords().stream()
                .map(VmPolicyEntity::getVmId).collect(Collectors.toList());
        if (vmIds.isEmpty()) return pager;
        List<VendingMachineEntity> vms = vendingMachineDao.getVmByIds(vmIds);
        List<VendingMachineViewModel> vmVOS = vms.stream().map(vm -> {
            VendingMachineViewModel vmVO = new VendingMachineViewModel();
            BeanUtils.copyProperties(vm, vmVO);
            NodeEntity node = nodeService.getById(vm.getNodeId());
            vmVO.setNodeName(node.getName());
            return vmVO;
        }).collect(Collectors.toList());
        pager.setCurrentPageRecords(vmVOS);
        return pager;
    }
}
